import { createStore } from 'vuex' ;
import Cookies from 'js-cookie' ;

const store = createStore({
    state() {  // 定义需要管理的数据 ， state 中定义的数据可以直接访问，但不能直接修改
        return {
            user: null , // 存储当前登录的用户名
            authorities: null , // 定义当前用户的权限列表
            sysId: null , // 存储当前系统的 ID
            refresh: null, // 刷新令牌
            token: null , // 给上传使用的令牌，其他未知不适用。
        }
    },
    mutations: {  // 同步方法，相当于 vue 中 methods
        setUserAndAuthorities(state, {user, auth:authorities, token, rememberMe, exp, refresh}) {
            state.user = user ;
            state.authorities = authorities ;
            state.token = token ; // 文件上传需要
            sessionStorage.setItem("RBAC-USER" , user);
            sessionStorage.setItem("RBAC-AUTHORITIES", JSON.stringify(authorities)) ;
            // 设置 AccessToken 令牌
            Cookies.set("RBAC-TOKEN" , token, {expires: new Date(new Date().getTime() + exp * 1000)}) ;
            if (rememberMe) {
                localStorage.setItem("RBAC-REFRESH-TOKEN", refresh) ;
            }else{
                sessionStorage.setItem("RBAC-REFRESH-TOKEN", refresh) ;
            }
        },
        changeSys(state, sysId) {
            state.sysId = sysId ;
            sessionStorage.setItem("sysId" , sysId) ;
        },
        resetSys(state) {
            state.sysId = null ;
            state.user = null ;
            state.authorities = null;
            state.refresh = null ;
            sessionStorage.removeItem("sysId");
            sessionStorage.removeItem("RBAC-USER");
            sessionStorage.removeItem("RBAC-AUTHORITIES");
            localStorage.removeItem("RBAC-REFRESH-TOKEN") ;
            sessionStorage.removeItem("RBAC-REFRESH-TOKEN") ;
            Cookies.remove("RBAC-TOKEN");
        },
        removeCookie(state) {
            Cookies.remove("RBAC-TOKEN");
        }
    },
    getters: { // 相当于 vue 中 computed
        rbacAuthorities(state) {
            state.authorities = state.authorities ?? (sessionStorage.getItem("RBAC-AUTHORITIES") == null ? [] : JSON.parse(sessionStorage.getItem("RBAC-AUTHORITIES")));
            return state.authorities ;
        },
        refreshToken(state) {
            state.refresh = state.refresh ?? (localStorage.getItem("RBAC-REFRESH-TOKEN") ?? sessionStorage.getItem("RBAC-REFRESH-TOKEN")) ;
            return state.refresh ;
        },
        currentUser(state) {
            state.user = state.user ?? sessionStorage.getItem("RBAC-USER") ;
            return state.user ;
        }
    }
})

export default store ;